package com.hyk.commonLib.common.utils;

import static android.content.Context.MODE_PRIVATE;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;

public class AppUtils {
    private static Application application;
    private static Thread mUiThread;
    private static final Handler sHandler = new Handler(Looper.getMainLooper());

    public static void init(Application application) {
        AppUtils.application = application;
        mUiThread = Thread.currentThread();
    }

    public static boolean hasInit() {
        return getAppContext() != null;
    }

    public static Context getAppContext() {
        return application.getApplicationContext();
    }

    public static Application getApplication() {
        return application;
    }

    public static boolean isUIThread() {
        return Thread.currentThread() == mUiThread;
    }

    public static boolean isMainThread() {
        return isUIThread();
    }

    public static void runOnUI(Runnable r) {
        sHandler.post(r);
    }

    public static boolean runOnUIDelayed(Runnable r, long delayMills) {
        return sHandler.postDelayed(r, delayMills);
    }

    public static void removeRunnable(Runnable r) {
        if (r == null) {
            sHandler.removeCallbacksAndMessages(null);
        } else {
            sHandler.removeCallbacks(r);
        }
    }

    public static String getPackageName() {
        return getAppContext().getPackageName();
    }

    public static String getAppName() {
        return ResUtils.getString(getAppContext().getApplicationInfo().labelRes);
    }

    /**
     * 判断程序是否在前台运行
     */
    static boolean isAppForeground() {
        ActivityManager am = (ActivityManager) AppUtils.getAppContext().getSystemService(Context.ACTIVITY_SERVICE);
        if (am == null) return false;
        List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
        if (info == null || info.size() == 0) return false;
        for (ActivityManager.RunningAppProcessInfo aInfo : info) {
            if (aInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return aInfo.processName.equals(AppUtils.getAppContext().getPackageName());
            }
        }
        return false;
    }

    /**
     * 是否有对象可以响应此intent
     */
    public static boolean isIntentAvailable(Intent intent) {
        PackageManager packageManager = getAppContext().getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    /**
     * 判断当前应用是否是debug状态
     */
    public static boolean isDebugMode() {
        try {
            ApplicationInfo info = getAppContext().getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断是否存在pckName包
     */
    public static boolean isPackageExist(String pckName) {
        try {
            PackageInfo pckInfo = getAppContext().getPackageManager().getPackageInfo(pckName, 0);
            if (pckInfo != null) return true;
        } catch (PackageManager.NameNotFoundException ignored) {
        }
        return false;
    }

    public static void bringToForeground() {
        try {
            /*获取ActivityManager*/
            ActivityManager activityManager = (ActivityManager) getAppContext().getSystemService(Context.ACTIVITY_SERVICE);

            /*获得当前运行的task(任务)*/
            List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                /*找到本应用的 task，并将它切换到前台*/
                if (taskInfo.topActivity.getPackageName().equals(getAppContext().getPackageName())) {
                    activityManager.moveTaskToFront(taskInfo.id, 0);
                    break;
                }
            }
        } catch (Exception ignored) {
        }
    }

    // 判断程序是否在后台
    public static boolean isBackground() {
        ActivityManager activityManager = (ActivityManager) AppUtils.getAppContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(AppUtils.getAppContext().getPackageName())) {
                return appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
            }
        }
        return false;
    }

    // 在业务代码中可传入BuildConfig.APPLICATION_ID；在库代码中获取不到正确的APPLICATION_ID，传空即可
    public static boolean isMainProcess(String appId) {
        boolean isMainProcess = false;
        try {
            if (StringUtils.isEmpty(appId)) {
                appId = getProcessName();
                if (StringUtils.isEmpty(appId)) {
                    return true;
                }
            }
            String mainProcessName = AppUtils.getApplication().getPackageManager().getPackageInfo(AppUtils.getPackageName(), 0).applicationInfo.processName;
            if (StringUtils.isNotEmpty(mainProcessName) && mainProcessName.equalsIgnoreCase(appId)) {
                isMainProcess = true;
            }
        } catch (Throwable ignored) {
        }

        return isMainProcess;


        // try {
        // Class<?> clazz = Class.forName("android.app.ActivityThread");
        // Method currentActivityThreadMethod = clazz.getDeclaredMethod("currentActivityThread");
        // currentActivityThreadMethod.setAccessible(true);
        // Object tCurrentActivityThread = currentActivityThreadMethod.invoke(null);
        //
        // Method tGetProcessNameMethod = clazz.getDeclaredMethod("getProcessName");
        // tGetProcessNameMethod.setAccessible(true);
        // String tProcessName = (String) tGetProcessNameMethod.invoke(tCurrentActivityThread);
        // return getAppContext().getPackageName().equalsIgnoreCase(tProcessName);
        // } catch (Throwable e) {
        //     return true;
        // }
    }

    public static String getProcessName() {
        String processName = "";
        int currentPid = Process.myPid();
        try {
            if (hasAgreePrivacy()) {
                List<ActivityManager.RunningAppProcessInfo> processInfoList = ((ActivityManager) AppUtils.getApplication().getSystemService(Context.ACTIVITY_SERVICE)).getRunningAppProcesses();
                for (ActivityManager.RunningAppProcessInfo processInfo : processInfoList) {
                    if (processInfo.pid == currentPid) {
                        processName = processInfo.processName;
                    }
                }
            } else {
                // 此方法为了隐私合规，可能获取失败
                File file = new File("/proc/" + android.os.Process.myPid() + "/cmdline");
                try (BufferedReader mBufferedReader = new BufferedReader(new FileReader(file))) {
                    processName = mBufferedReader.readLine().trim();
                }
            }
        } catch (Throwable ignored) {
        }
        return processName;
    }

    public static boolean hasAgreePrivacy() {
        return AppUtils.getAppContext().getSharedPreferences("_Privacy_hykCommon_", MODE_PRIVATE).getBoolean("agreePrivacy", false);
    }

    public static void markAgreePrivacy() {
        SharedPreferences preferences = AppUtils.getAppContext().getSharedPreferences("_Privacy_hykCommon_", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("agreePrivacy", true);
        editor.commit();
    }

    public static void exit() {
        System.exit(0);
    }
}
